<template>
  <div class="imgdiv">
    <el-row class="eldiv1">
      <el-col :span="24">
        <span>{{tableSetJson.label}}</span>
        <div class='upload-img-div'>
          <el-upload
            :action="fileUrl"
            :disabled="imgDisplay"
            :data="fileUploadData"
            :headers="headers"
            ref="imgUpload"
            list-type="picture-card"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            accept=".jpg,.jpeg,.png,.gif,.html,.bmp"
            :on-change="getChangeStringValue"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
            multiple>
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="mulrenum.rnuRadioContent" alt="">
          </el-dialog>
        </div>
        
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { uploadFile_Url, deleteFileUrl, executionSql,showPictureByidUrl } from "@/config/api"
import qs from 'qs'
import { constants } from 'crypto';

export default {
  name: "imgupload",
  props: {
    /* 父组件传过来的数据 */
    tableSetJson: {
      type: Object
    },
    renumin: {
      type: Object
    },
    linkTableType: {
      type: String
    }
  },
  data() {
    return {
      fileList: [],
      fileUrl: '',//上传地址
      fileUploadData: {
        raid:"",
        linkTableType:"",
        rnucode: "",
        project: "",
        fileName: ""
      },//上传参数
      imgDisplay:false,
      mulrenum: this.renumin,
      dialogVisible: false,
      filetemp: [],
      token: ""
      // fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
    };
  },
  created() {
    // console.log(this.tableSetJson);
    this.token = localStorage.getItem("set_token");
    console.log("this.tableSetJson.display=====>>"+this.tableSetJson.display);
    if( this.tableSetJson.display !=null && this.tableSetJson.display != undefined)
    {
      console.log("12312312312312321=====>>");
      this.imgDisplay = this.tableSetJson.display ;
    }
    this.comUploadParam();
    this.queryUploadFile();
  },
  computed: {
    headers() {
      return{
        "Authorization": this.token // 直接从本地获取token就行
      }
    }
  },
  methods: {
    //初始化上传参数
    comUploadParam() {
      this.fileUrl = this.axios.defaults.baseURL+"/quality/common/multifilesUpload";
      this.fileUploadData = {
        raid: this.renumin.raId,
        linkTableType: this.linkTableType,
        rnucode: this.tableSetJson.name,
        project: localStorage.getItem("project_id"),
        fileName: ""
      }
    },
    uploadSuccess(response, file, fileList) {
      if (response.success === true) {
        this.$message.success('上传成功！');
        this.$refs.imgUpload.clearFiles();
        this.queryUploadFile();
      } else {
        this.$message.error('上传失败！')
      }
    },
    /* 往父节点传值的方法 */
    getChangeStringValue() {
      this.mulrenum.rnuCode = this.tableSetJson.name;
      this.mulrenum.rnuType = this.tableSetJson.type;   
      this.mulrenum.rnuNo = this.tableSetJson.orderno;
      // this.fileList = fileList;
      // 数组添加唯一数据方法
      // Array.prototype.push_unique = function () {
      //   for (var i = 0; i < arguments.length; i++) {
      //     var ele = arguments[i];
      //     if (this.indexOf(ele) == -1) {
      //         this.push(ele);
      //     }
      //   }
      // };
      // // 文件只能是图片格式和禁止重复上传
      // var temp = [];
      // var isExist = this.filetemp.indexOf(file.name) !== -1;
      // var hash = {};
      // var notPicture = false;
      // this.fileList = this.fileList.reduce(function (item, next) {
      //   var testmsg = next.name.substring(next.name.lastIndexOf('.')+1).toLowerCase();
      //   const extension1 = testmsg === 'jpeg';
      //   const extension2 = testmsg === 'jpg';
      //   const extension3 = testmsg === 'png';
      //   const extension4 = testmsg === 'gif';
      //   const extension5 = testmsg === 'bmp';
      //   notPicture = !extension1 && !extension2 && !extension3 && !extension4 && !extension5;
      //   if (!notPicture) {
      //     hash[next.name] ? '' : hash[next.name] = true && item.push(next);
      //     temp.push_unique(next.name);
      //   }
      //   return item;
      // }, []);
      // this.filetemp = temp;
      // // console.log("notPicture的值=====>>>>>" + notPicture);
      // if(notPicture) {
      //     this.$message({
      //         message: '上传文件只能是图片格式!',
      //         type: 'error'
      //     });
      // }
      // console.log("fileTemp====>>>>" + JSON.stringify(this.filetemp));
      // console.log("fileList====>>>>" + JSON.stringify(this.fileList));
      // console.log("file.name====>>>>" + file.name);
      // console.log("isExist====>>>>" + this.filetemp.indexOf(file.name));
      // if (this.filetemp.indexOf(file.name) !== -1) {
      //   this.$message({
      //         message: '不允许重复上传文件!',
      //         type: 'error'
      //     });
      // }
      // console.log("数组是否含有重复对象====>>>>" + this.fileList);
      // this.mulrenum.fileDes = this.fileList;
      //console.log("============>>>>>>" + JSON.stringify(this.tableSetJson));
      //console.log("dateinput组件输出对象：======>>>>>" + JSON.stringify(this.mulrenum));
      this.$emit("listenToImgUpload", this.mulrenum);
    },
    setPlaceholder() {
      return this.tableSetJson.texttip;
    },
    handleRemove(file, fileList) {
      // 移除的时候就在临时数组先删除该文件名
      // var index = this.filetemp.indexOf(file.name);
      // if (index > -1) {
      //   this.filetemp.splice(index, 1);
      // }
      // this.getChangeStringValue(file, fileList);
      deleteFileUrl({
        docId: file.docId
      }).then(res => {
        if (res.data.success === true) {
          this.$message.success('删除成功！');
        } else {
          this.$message.error('删除失败：' + res.data.msg);
        }
      });
    },
    handlePictureCardPreview(file) {
      this.mulrenum.rnuRadioContent = file.url;
      this.dialogVisible = true;
    },
    queryUploadFile() {
      this.fileList = [];
      if (this.renumin.raId != null && this.renumin.raId != "") {
        showPictureByidUrl({
          raid: this.renumin.raId,
          rnucode: this.tableSetJson.name
        }).then(res => {
          if (res.data.success === true) {
            for (var index = 0; index < res.data.data.length; index++) {
              var tempFile = {
                docId:"",
                name:"",
                url:""
              }
              tempFile.docId = res.data.data[index].docId;
              tempFile.name = res.data.data[index].docName;
              tempFile.url = res.data.data[index].image;
              this.fileList.push(tempFile);
            }
          } else {
            this.fileList = [];
          }
        });
        // executionSql({
        //   dsCode:"ZL_DOCUMENTFILES",
        //   docRelId: this.renumin.raId,
        //   docType: "1"
        // }).then(res => {
        //   if (res.data.success === true) {
        //     for (var index = 0; index < res.data.data.length; i++) {
        //       var tempFile = {
        //         name:"",
        //         url:""
        //       }
        //       tempFile.name = res.data.data[index].docId;
        //       tempFile.url = res.data.data[index].image;
        //       this.fileList.push(tempFile);
        //     }
        //   } else {
        //     this.fileList = [];
        //   }
        // });
      } else {
        this.fileList = [];
      }
    },
    beforeUpload(file) {
      if (this.renumin.raId == null || this.renumin.raId == "") {
        this.$message.error('未生成填报，不允许上传！');
        return false;
      }
      let orgfileName = file.name;
      this.fileUploadData.fileName = orgfileName;
    }
  }
};
</script>
<style>
.imgdiv {
  border: 1px solid #dedede;
  width: 724px;
  margin-left: 5px;
  margin-top: 5px;
  margin-bottom: 5px;
  background-color: #f3f3f3;
}
.upload-div {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  width: 360px;
  height: 180px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.upload-img-div .upload-img-div-child {
  width: 150px;
  height: 150px;
  margin-right: 10px;
  position: relative;
  overflow: hidden;
  float: left;
}
.upload-img-div>.upload-img-div-child span {
  position: absolute;
  width: auto;
  height: auto;
  right: 5px;
  bottom: 3px;
}
.room-img {
  width: 150px;
  height: 150px;
}
.room-img:hover {
  opacity: 1;
}
</style>
